import groovyx.net.http.HTTPBuilder  
import groovyx.net.http.HttpResponseException  
import static groovyx.net.http.Method.GET  
import static groovyx.net.http.ContentType.JSON  
import static groovyx.net.http.ContentType.URLENC 
import org.grails.plugins.lookups.*

class UpService {

    boolean transactional = true

    def schoolClear(schoolId){
        def school = School.get(schoolId)

        if (school) {

            def classes = Classes.findAllBySchoolAndGradeLessThan(school , 7)
            // 清除之前的快照
            classes.each{aClass ->
                def cbs = ClassBackup.findAllByClasses(aClass)
                cbs.each{aClassBackup ->
                    def sbs = StudentBackup.findAllByClassBackup(aClassBackup)
                    sbs.each{aStudentBackup ->
                        aStudentBackup.delete()
                    }
                    aClassBackup.delete()
                }
                
                log.info "clear snapshot!"
            }
        }
    }


    def schoolUp(schoolId , term , uri) {
        def school = School.get(schoolId)
        if (school) {

            def classes = Classes.findAllBySchoolAndGradeLessThan(school , 7)
            
            classes.each{aClass ->
            // 备份班级
                def classBackup = new ClassBackup()
                    classBackup.level = aClass.level//等级  （小学、初中、高中）
                    classBackup.grade = aClass.grade // 年级 (一年级....)
                    classBackup.team = aClass.team // 班
                    classBackup.master = aClass.master  //班主任
                    classBackup.term = term //学期
                    classBackup.classes = aClass
                    aClass?.teacherCourseClasses?.each{
                        classBackup.addToTeachers(it.teacher)
                    }
                    if (classBackup.validate()) {
                        classBackup.save()
                    }else{
                        classBackup.errors.each{
                            log.info it
                        }
                    }
                    
                    
                 // 备份班级下的学生   
                    aClass?.student?.each{aStudent ->
                        def studentBackup = new StudentBackup()
                        studentBackup.name = aStudent.name // 姓名    
                        studentBackup.sex =  aStudent.sex //性别
                        studentBackup.birthday =  aStudent.birthday // 生日
                        studentBackup.classBackup = classBackup
                        studentBackup.level =   aStudent.level
                      
                        studentBackup.student =  aStudent
                        studentBackup.term   = term
                
                        if (studentBackup.validate()) {
                            studentBackup.save()
                        }else{
                            studentBackup.errors.each{
                                log.info it
                            }
                        }
                        classBackup.addToStudent(studentBackup)
                        classBackup.save()
                    }

                    //升级班级
                    aClass.grade = aClass.grade + 1
                    aClass.save()
                    upBlogClass(aClass,uri)
                    
//                    throw new RuntimeException("事务测试") 
 
            }
        }
        return true
    }

    def upBlogClass(classes,uri){
        def http = new HTTPBuilder(uri)
        def name = URLEncoder.encode("${classes.level}${Lookup.valueFor('grades', classes.grade)}${Lookup.valueFor('teams', classes.team)}",'UTF-8')
        try {
         def postBody = [hostId:"${classes.id}",name:"${name}"]
            http.post( path: '', body: postBody, 
                       requestContentType: URLENC) { resp, json ->  
                        log.info(resp.statusLine)     
                        log.info("Query response: ") 
                        log.info(json.message)
            }
        }catch (Exception ex ) {  
        }
        
    }
}
